package com.maotai.llzhou.thread;

import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.http.client.config.RequestConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.MaotaiString;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.bean.ProductInfo;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.util.FaceUtil;
import com.maotai.llzhou.util.HttpClientUtilNew;
import com.maotai.llzhou.util.IPFactory;
import com.maotai.llzhou.util.JSUtil;

/**
 * 登录并且抢购
 */
public class MaotaiAuditThread extends Thread {

	@Resource(name = "maotaiService")
	private MaotaiService maotaiService;
	private Map<String, Object> zhanghao;
	private String ipAndPort;
	private MaotaiWebCookie mwc;
	private Map<String, Object> shenfenMap;
	private Map<String, Object> tokenMap;

	public MaotaiAuditThread(MaotaiService maotaiService,
			Map<String, Object> zhanghao, String ipAndPort, MaotaiWebCookie mwc,
			Map<String, Object> shenfenMap, Map<String, Object> tokenMap) {
		super();
		this.maotaiService = maotaiService;
		this.zhanghao = zhanghao;
		this.ipAndPort = ipAndPort;
		this.mwc = mwc;
		this.shenfenMap = shenfenMap;
		this.tokenMap = tokenMap;
	}

	public MaotaiWebCookie getMwc() {
		return mwc;
	}

	public Map<String, Object> getShenfenMap() {
		return shenfenMap;
	}
	public void setShenfenMap(Map<String, Object> shenfenMap) {
		this.shenfenMap = shenfenMap;
	}
	public Map<String, Object> getTokenMap() {
		return tokenMap;
	}
	public void setTokenMap(Map<String, Object> tokenMap) {
		this.tokenMap = tokenMap;
	}
	public void setMwc(MaotaiWebCookie mwc) {
		this.mwc = mwc;
	}

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public MaotaiService getMaotaiService() {
		return maotaiService;
	}

	public void setMaotaiService(MaotaiService maotaiService) {
		this.maotaiService = maotaiService;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	@Override
	public void run() {
		try {
			int mtBizId = 0;
			String auth = zhanghao.get("auth")+"";
			String zimId = "";
            String bizId = "";
            String name = zhanghao.get("name")+"";
            String certNumber = zhanghao.get("certNumber")+"";
            if("".equals(auth)||"null".equals(auth)){
            	shenfenMap.put("usestatus", "0");
				maotaiService.updateShenFenStatus(shenfenMap);
            	zhanghao.put("initstatus", "0");
				maotaiService.updateZhanghaoInitStatus(zhanghao);
	        	return;
            }
            
			HttpClientUtilNew hcu = HttpClientUtilNew.getInstance();
			// 增加代理
			RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);
			
			/**
			 * 新增扫脸功能
			 */
			//访问预约页面
//			mwc = hcu.sendHttpGetProxyIndex(MaotaiString.APPLY_BEGIN_URL, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
	        //点击预约
//	        String signurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/switch?sign="+JSUtil.excuFunctionA("EMAOTAI_"+zhanghao.get("memberId"))+"&appCode=1&_t="+System.currentTimeMillis();
//	        mwc = hcu.sendHttpGetProxy(signurl, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
	        //2018-09-08
	        //信用体系
	        String auditurl = "https://i.emaotai.cn/yundt-application-trade-core/api/v1/yundt/trade/memberdoc/audit/get?appCode=1&_t="+System.currentTimeMillis();
	        mwc = hcu.sendHttpGetProxy(auditurl, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
	        
	        //清楚下缓存
	        //String clearurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/clear?mtBizId=2&appCode=1&_t="+System.currentTimeMillis();
	        //mwc = hcu.sendHttpGetProxy(clearurl, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
	        //TODO
			//扫码接收预约
	        //发起二维码扫描
	        String compressurl1 = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/compress?mtBizId=2&faceverify=scan&auth="+auth+"&appCode=1&_t="+System.currentTimeMillis();
	        String yuyuereferer1 = "https://www.emaotai.cn/smartsales-b2c-web-pc/sign/signUp?info="+auth;
	        //接收二维码扫描
	        mwc = hcu.sendHttpGetProxy(compressurl1, mwc, config, yuyuereferer1);
	        System.out.println(zhanghao.get("code")+"----提示信用二维码页面-------"+mwc.getContent());
	        //信用扫描二维码
	        String auditUrl = "https://i.cmaotai.com/yundt-application-trade-core/api/v1/yundt/trade/memberdoc/audit/get";
	        mwc = hcu.sendHttpGetAppProxy(auditUrl, mwc, config, null);
	        System.out.println(zhanghao.get("code")+"----获取实名结果----" + mwc.getContent());
	        JSONObject resultCode = JSONObject.parseObject(mwc.getContent());
	        
	        if(resultCode.getIntValue("resultCode")==401){
	        	zhanghao.put("loginstatus", "0");
	        	maotaiService.updateZhanghaoLoginStatus(zhanghao);
	        	zhanghao.put("initstatus", "0");
				maotaiService.updateZhanghaoInitStatus(zhanghao);
				shenfenMap.put("usestatus", "0");
				maotaiService.updateShenFenStatus(shenfenMap);
	        	return;
	        }
            if(resultCode.getIntValue("resultCode")==-1){
            	shenfenMap.put("usestatus", "0");
				maotaiService.updateShenFenStatus(shenfenMap);
				zhanghao.put("initstatus", "x");
				maotaiService.updateZhanghaoInitStatus(zhanghao);
            	return;
            }
	        if(mwc.getContent().contains("docNo")){
	        	JSONObject data = JSONObject.parseObject(mwc.getContent()).getJSONObject("data");
	        	String docNo = data.getString("docNo");
	        	String realName = data.getString("realName");
	        	zhanghao.put("docNo", docNo);
	        	zhanghao.put("realName", realName);
	        	maotaiService.insertMaotaiAudit(zhanghao);
	        	shenfenMap.put("usestatus", "0");
				maotaiService.updateShenFenStatus(shenfenMap);
	        	return;
	        }
//	        Thread.sleep(5000);
	        Map<String, Object> tokenMap = maotaiService.getTokenRandom();
//	        shenfenMap = maotaiService.getShenFengRandom();
	        String token = tokenMap.get("token")+"";
	        //获得metainfo
	        JSONObject uploadJ = new JSONObject();
	        uploadJ.put("apdidToken",token+""+System.currentTimeMillis()) ;
	        uploadJ.put("appName","com.emaotai.ysapp") ;
	        uploadJ.put("appVersion",ProductInfo.PRODUCT_VERSION) ;
	        uploadJ.put("bioMetaInfo","3.3.0:98304,0") ;
	        uploadJ.put("deviceModel","HTC Rezound"+""+System.currentTimeMillis()) ;
	        uploadJ.put("deviceType","android") ;
	        uploadJ.put("osVersion","6.0.1") ;
	        uploadJ.put("zimVer","1.0.0") ;
//	        String realname = shenfenMap.get("name")+"";
//	        String shenfenzheng = shenfenMap.get("shenfenzheng")+"";
	        String inturl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/init";
	        //System.out.println(certNumber+"----"+name);
//	        String postData = "auditType=1&certNumber="+shenfenzheng+"&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName="+URLEncoder.encode(realname,"utf-8");
//	        String postData = "auditType=1&certNumber=320922198607240034&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName=%E5%91%A8%E4%BA%AE%E4%BA%AE";
//	        String postData = "auditType=1&certNumber=341122198904270433&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName="+URLEncoder.encode("王涛","utf-8");
	        String postData = "auditType=1&certNumber="+certNumber+"&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName="+URLEncoder.encode(name,"utf-8");
	        for(int i=0;i<10;i++) {
	        	 mwc = hcu.sendHttpPostAppProxy(inturl, mwc, postData, config);
	            // "bizId" : "EMAOTAI_20180814093735856536",
	            System.out.println(zhanghao.get("code")+"----初始化信用摄像头----" + mwc.getContent());
	            if(resultCode.getString("resultMsg").contains("失败")){
		        	shenfenMap.put("usestatus", "0");
					maotaiService.updateShenFenStatus(shenfenMap);
					zhanghao.put("initstatus", "f");
					maotaiService.updateZhanghaoInitStatus(zhanghao);
					return;
		        }
	            if (mwc.getContent().contains("抱歉")||mwc.getContent().contains("query")) {
	            	Thread.sleep(1000);
	                continue;
	            } else {
	                break;
	            }
	            
	        }
	       
	        //获取信用返回的data
	        if(mwc!=null && mwc.getContent()!=null){
	            JSONObject initJson = JSON.parseObject(mwc.getContent()).getJSONObject("data");
	            zimId = initJson.getString("zimId");
	            bizId = initJson.getString("bizId");
	            
	        }
	        boolean isFaceXinYong = FaceUtil.faceToken(token,zimId,config,zhanghao);
	        if(!isFaceXinYong){
				zhanghao.put("initstatus", "0");
				maotaiService.updateZhanghaoInitStatus(zhanghao);
				shenfenMap.put("usestatus", "0");
				maotaiService.updateShenFenStatus(shenfenMap);
	        	return;
	        }
//	        Thread.sleep(8000);
	        //查询验证结果
	        String queryurl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/query?zimId="+zimId+"&bizId="+bizId+"&mtBizId="+mtBizId+"&auditType=1";
	        hcu.sendHttpGetAppProxy(queryurl, mwc, config, null);
	        System.out.println(zhanghao.get("code")+"----识别结束提交服务器----"+mwc.getContent());
	        String refererurl = "https://www.emaotai.cn/smartsales-b2c-web-pc/sign/signUp?info=eyJpdGVtTmFtZSI6IuOAkOiMheWPsOWVhuWfjumihOe6pui0reS5sOOAkei0teW3nuiMheWPsOmFku%2b8iOaWsOmjnuWkqe%2b8iTUzJXZvbCA1MDBtbO%2b8iOWVhuWTgee8luWPt%2b%2b8mjc0Me%2b8iSIsImltZ1VybCI6Imh0dHBzOi8vcHJvZC1vc3MuZW1hb3RhaS5jbi9zdXBwbHljaGFpbi1kZXYvdGVzdC9pbWcvQ3lma2RuUDVGcy5qcGciLCJza3VJZCI6IjExODA3MzE3OTk5MzE4MDg3NzEiLCJpdGVtSWQiOiIxMTgwNzMxNzk5OTI0NDY4NzQwIiwic2hvcElkIjoiMTE3Mzc3MzE3ODI2NDI1OTU4NCJ9";

	        String initUrl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/qrquery?mtBizId="+mtBizId+"&appCode=1";
	        mwc = hcu.sendHttpGetProxy(initUrl,mwc,config,refererurl);
	        System.out.println(zhanghao.get("code")+"----查询识别结果----"+mwc.getContent());
	        if(mwc!=null && !mwc.getContent().contains("success")){
	            System.out.println("识别结果未成功");
	            for(int i=0;i<1;i++){
	            	mwc = hcu.sendHttpGetProxy(initUrl,mwc,config,refererurl);
	                System.out.println("maotaiAppCookie---"+mwc.getContent());
	                if(mwc!=null && mwc.getContent().contains("success")){
	                    break;
	                }
	            }
	        }
	        String saveurl = "https://i.cmaotai.com/yundt-application-trade-core/api/v1/yundt/trade/memberdoc/audit/save";
	        //auditResult=1&auditType=1&docNo=320922198607240034&docType=1&realName=%E5%91%A8%E4%BA%AE%E4%BA%AE
	        //用最新的身份证去修改数据库数据
//	        Map<String, Object> shenfenMap = maotaiService.getShenFengRandom();
//	        System.out.println(shenfenMap);
//	        String newShenfenzheng = shenfenMap.get("shenfenzheng")+"";
//	        String newName = shenfenMap.get("name")+"";
	         String saveData = "auditResult=1&auditType=1&docNo="+certNumber+"&docType=1&realName="+URLEncoder.encode(name,"utf-8");
	        //2018-11-04 将已经买过的账号对应的脸修改为别的，把有数据的脸空出来去实名预约成功的号，这样来循环
	         
//	        String saveData = "auditResult=1&auditType=1&docNo="+newShenfenzheng+"&docType=1&realName="+URLEncoder.encode(newName,"utf-8");
//	        String saveData = "auditResult=1&auditType=1&docNo="+newShenfenzheng+"&docType=1&realName="+newName;
	        mwc = hcu.sendHttpPostAppProxy(saveurl, mwc, saveData, config);
	        System.out.println(zhanghao.get("code")+"----身份信息添加结束----"+mwc.getContent());
//	        zhanghao.put("initstatus", "0");
//			maotaiService.updateZhanghaoInitStatus(zhanghao);
	        //修改身份证状态
	        //maotaiService.updateShenFenStatus(shenfenMap);
	        //到此信用体系结束，重新去预约
//	        if(mwc.getContent().contains("该证件已使用")){
//				zhanghao.put("initstatus", "0");
//				maotaiService.updateZhanghaoInitStatus(zhanghao);
//	        }
		} catch (Exception e) {
			System.out.println(zhanghao.get("code")+"--"+e.getMessage()+" : throws auditinit exception ");
			try {
				shenfenMap.put("usestatus", "0");
				maotaiService.updateShenFenStatus(shenfenMap);
				zhanghao.put("initstatus", "0");
				maotaiService.updateZhanghaoInitStatus(zhanghao);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}



}
